package com.itheima.health.mobile.lock;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.RetryNTimes;

/**
 * @Author gentleman Ma
 * @Date created in 2020/1/4
 * @description 监听节点变化实例
 * @Version 1.0
 */

public class NodeCacheTest {
    public static void main(String[] args) throws Exception {
        //超时重连策略，每1000毫秒重试一次，重试10次
        RetryPolicy retryPolicy = new RetryNTimes(10, 1000);
        //创建客户端
        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
        //开启客户端
        client.start();
        final NodeCache nodeCache = new NodeCache(client,"/curator/lock");

        nodeCache.start();

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData currentData = nodeCache.getCurrentData();
                if (null == currentData){
                    System.out.println("[数据监听]节点删除:"+nodeCache.getPath());
                }else {
                    System.out.println("[数据监听]"+nodeCache.getPath()+":"+new String(currentData.getData()));

                }
            }
        });

        System.in.read();

        nodeCache.close();
        client.close();

    }
}
